from django.db import models
from django.contrib.auth.models import User
from books.models import Book

class Borrowing(models.Model):
    STATUS_CHOICES = (
        ('active', '借阅中'),
        ('returned', '已归还'),
        ('overdue', '逾期'),
    )

    book = models.ForeignKey(Book, on_delete=models.PROTECT, related_name='borrowings', verbose_name='图书')
    borrower = models.ForeignKey(User, on_delete=models.PROTECT, related_name='borrowings', verbose_name='借阅者')
    borrow_date = models.DateTimeField(auto_now_add=True, verbose_name='借阅日期')
    due_date = models.DateTimeField(verbose_name='应还日期')
    return_date = models.DateTimeField(null=True, blank=True, verbose_name='归还日期')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='active', verbose_name='状态')
    notes = models.TextField(blank=True, verbose_name='备注')

    class Meta:
        verbose_name = '借阅记录'
        db_table = 'api_borrowing'
        verbose_name_plural = verbose_name
        ordering = ['-borrow_date']

    def __str__(self):
        return f"{self.borrower.username} - {self.book.title}"

    def is_overdue(self):
        """检查是否逾期"""
        if self.return_date:
            return False
        from django.utils import timezone
        return timezone.now() > self.due_date

    def calculate_fine(self):
        """计算逾期罚款（假设每天1元）"""
        if not self.is_overdue():
            return 0

        from django.utils import timezone
        overdue_days = (timezone.now() - self.due_date).days
        return overdue_days * 1  # 每天罚款1元
